<?php
/**
 * Description: 获取专项练习知识点题目
 * User: devforma
 * Date: 15/4/9
 * Time: 14:27
 */

require __DIR__ . '/includes/utils.php';
class GetNoteQuestions implements iController {

    private $userId, $availableNotes;

    function __construct() {

        $this->paperType = array(
            'note' => '专项练习',
            'error' => '错题练习',
            'collect' => '收藏练习'
        );
    }

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;
        
        if (validateUser($queryArgs) !== 1 || empty($queryArgs['type']) || !in_array($queryArgs['type'], array('note', 'collect', 'error'))) {
            return genOutput(1000);
        }

        $this->userId = intval($queryArgs['user_id']);

        //获取该用户能看到的知识点
        $userData = getUserData($this->userId);
        if (empty($userData) || empty($userData->note_info))
            return genOutput(1000);

        //获取知识点层次结构
        $hierarchy = getNewNoteHierarchy();

        //用户可见的知识点列表
        $this->availableNotes = array_keys(normalizeUserNoteInfo($userData->note_info));

        //知识点id参数统一化
        if (!empty($queryArgs['note_id']) && filter_var($queryArgs['note_id'], FILTER_VALIDATE_INT)) {
            $originalNoteId = $queryArgs['note_id'];
        } elseif (!empty($queryArgs['hierarchy_3']) && filter_var($queryArgs['hierarchy_3'], FILTER_VALIDATE_INT)) {
            $originalNoteId = $queryArgs['hierarchy_3'];
        } elseif (!empty($queryArgs['hierarchy_2']) && filter_var($queryArgs['hierarchy_2'], FILTER_VALIDATE_INT)) {
            $originalNoteId = $queryArgs['hierarchy_2'];
        } elseif (!empty($queryArgs['hierarchy_1']) && filter_var($queryArgs['hierarchy_1'], FILTER_VALIDATE_INT)) {
            $originalNoteId = $queryArgs['hierarchy_1'];
        } else {
            return genOutput(1000);
        }

        //查询所给知识点下的叶子知识点
        $noteIds = getLeafNotesFromHierarchy($originalNoteId, $this->availableNotes);
        if (empty($noteIds)) return genOutput(1001);

        //按知识点来生成题目
        $questions = $this->getQuestionIdsByNote($queryArgs['type'], $noteIds);

        //生成试卷名称
        $paperName = '知识点专项练习 - '.$hierarchy[$originalNoteId]['name'];

        //构建题目列数据
        if (!empty($questions)) {
            $qids = array();
            foreach ($questions as $q) {
                $qids[] = $q['id'];
            }

            $result = $cmsdb->insert('qb_relationship_user_paper', array(
                'user_id' => $this->userId,
                'paper_id' => 0,
                'paper_type' => getPaperType($this->paperType[$queryArgs['type']])->type_id,
                'paper_title' => $paperName,
                'question_info' => implode(',', $qids),
                'create_time' => date('Y-m-d H:i:s'),
                'status' => 0,
                'duration' => 0,
                'right_count' => 0,
                'total_count' => 0,
                'extra_info' => serialize(array('note_id' => $originalNoteId)),
                'terminal_type' => empty($_GET['terminal_type']) ? '' : trim($_GET['terminal_type'])
            ));

            if (!empty($result)) {
                return genOutput(1, array(
                    'paper_id' => intval($cmsdb->lastInsertId()),
                    'paper_title' => $paperName,
                    'duration' => 900,
                    'questions' => $questions
                ));
            }
        }

        return genOutput(1001);
    }

    /**
     * 根据知识点获取题目
     *
     * @param $type
     * @param $noteIds
     * @return array
     */
    private function getQuestionIdsByNote($type, $noteIds) {
        global $uddb;

        $table = $uddb->table($uddb->qbUserTests)->sublist($this->userId);

        if ($type == 'collect') {
            $sql = "SELECT DISTINCT(`question_id`) FROM `{$table}` WHERE `user_id`=:user_id AND
             `note_id` IN (".implode(',', $noteIds).") AND `is_collected`=1 AND `collect_time` IS NOT NULL";

        } elseif ($type == 'error') {
            $sql = "SELECT DISTINCT(`question_id`), `user_answer` FROM `{$table}` WHERE `user_id`=:user_id AND
             `note_id` IN (".implode(',', $noteIds).") AND `is_right`=0 AND `test_time` IS NOT NULL";
        } else {
            return getNoteQuestions($noteIds, 15, $this->userId, true);
        }

        $qids = $uddb->getCol($sql, array(':user_id' => $this->userId));

        if (count($qids) >= 15) {
            shuffle($qids);

            $newIds = array();
            $keys = array_rand($qids, 15);
            foreach ($keys as $key) {
                $newIds[] = $qids[$key];
            }
            return getQuestionsByIds($newIds);
        } else {
            return getQuestionsByIds($qids);
        }
    }
}